package com.epfresh.supplier.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BuyerConstant;
import com.epfresh.api.global.MessageCentre;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.http.RequestManager;
import com.epfresh.api.utils.InputControl;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.supplier.BuildConfig;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.api.entity.User;
import com.epfresh.api.utils.T;
import com.epfresh.supplier.entity.EmployEntity;
import com.epfresh.supplier.entity.MerChantInfo;
import com.epfresh.supplier.entity.MerchantMember;
import com.epfresh.supplier.entity.StaffInfo;
import com.epfresh.supplier.entity.WebTokenReponse;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.epfresh.api.constant.*;
import com.google.gson.reflect.TypeToken;
import com.tencent.mmkv.MMKV;

public class LoginActivity extends BaseActivity {

    public static final String TAG = "LoginActivity";
    // 手机号,验证码，密码
    private String phoneSting, passwordString;
    private EditText phoneEt;
    private EditText passwordEt;
    private Button sureBu;
    private ImageView look_password;
    private FrameLayout look_frame;
    TextView forgetTv;
    TextView registerTv;
    Intent intent;
    String phonePreString, passwordPreString;

    private boolean isRelogin;
    private boolean isBackLast;
    private TextView tv_crash, tv_rc, tv_beta;
    private FrameLayout deleteFrame, deleteFrame2;
    //private String access_token;

//    public static boolean isForeground;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        intent = new Intent(this, HomeNewActivity.class);
        SharedPreferences preferences = getSharedPreferences(Constant.USERINFO,
                Activity.MODE_PRIVATE);
        phonePreString = preferences.getString(Constant.MOBILE, "");
        passwordPreString = preferences.getString(Constant.PASSWORD, "");
        phoneEt.setText(phonePreString);
        passwordEt.setText(passwordPreString);
        phoneEt.setSelection(phoneEt.getText().length());
        forgetTv = (TextView) findViewById(R.id.forget);
        registerTv = (TextView) findViewById(R.id.register);
        forgetTv.setOnClickListener(this);
        registerTv.setOnClickListener(this);
        ivBack.setVisibility(View.VISIBLE);
        if (savedInstanceState != null) {
            getIntent().putExtra("relogin", savedInstanceState.getBoolean("relogin"));
            getIntent().putExtra("backLast", savedInstanceState.getBoolean("backLast"));
        }
        isRelogin = getIntent().getBooleanExtra("relogin", false);
        isBackLast = getIntent().getBooleanExtra("backLast", false);
        if (!isRelogin) {
            BaseApplication.loginActivityCount++;
        }
        int env = BuildConfig.ENV;
        if (env == 0) {//正式版本
            findViewById(R.id.v_env).setVisibility(View.GONE);
        } else if (env > 0) {//测试版本
            findViewById(R.id.v_env).setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean("relogin", isRelogin);
        outState.putBoolean("backLast", isBackLast);
        super.onSaveInstanceState(outState);
    }

    /**
     * 监听点击事件
     */
    boolean passwordflag = false;
    String password = "";

    public void initView() {
        setContentView(R.layout.activity_login);
        deleteFrame = findViewById(R.id.delete_frame);
        deleteFrame2 = findViewById(R.id.delete_frame2);
        passwordEt = findViewById(R.id.password_number);
        phoneEt = findViewById(R.id.phone_number);
        sureBu = findViewById(R.id.sure);
        look_password = findViewById(R.id.look_password);
        look_frame = findViewById(R.id.look_frame);
        tv_crash = findViewById(R.id.tv_crash);
        tv_rc = findViewById(R.id.tv_rc);
        tv_beta = findViewById(R.id.tv_beta);
        tv_rc.setOnClickListener(this);
        tv_beta.setOnClickListener(this);
        sureBu.setOnClickListener(this);
        look_frame.setOnClickListener(this);
        toolbarTitle.setText("用户登录");
        actionbar.setVisibility(View.GONE);

        deleteFrame.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phoneEt.setText("");
            }
        });
        deleteFrame2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                passwordEt.setText("");
            }
        });

        phoneEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().equals("")) {
                    deleteFrame.setVisibility(View.INVISIBLE);
                } else {
                    deleteFrame.setVisibility(View.VISIBLE);
                }
            }
        });

        passwordEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().equals("")) {
                    deleteFrame2.setVisibility(View.GONE);
                } else {
                    deleteFrame2.setVisibility(View.VISIBLE);
                }
            }
        });
        switchEnv();
        logoutSuccess();
    }

    private void switchEnv() {
        int env0 = ApplicationHelper.getInstance().getEnv();
        if (env0 == 1) {
            tv_crash.setText("切换环境(当前是预发布环境)");
        } else if (env0 == 2) {
            tv_crash.setText("切换环境(当前是测试环境)");
        }
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.baseback:
                // 返回上一页

                onBackPressed();
                break;
            case R.id.look_frame:
                if (!passwordflag) {
                    look_password.setImageDrawable(getResources().getDrawable(R.mipmap.login_03_));
                    passwordEt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    look_password.setImageDrawable(getResources().getDrawable(R.mipmap.login_03));
                    passwordEt.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                passwordflag = !passwordflag;
                passwordEt.postInvalidate();
                CharSequence text = passwordEt.getText();
                if (text instanceof Spannable) {
                    Spannable spanText = (Spannable) text;
                    Selection.setSelection(spanText, text.length());
                }
                break;
            case R.id.sure:
                if (InputControl.isEmpty(phoneEt)) {
                    T.toast("请输入手机号");
                    return;
                }
                if (!InputControl.isPhoneNumber(phoneEt)) {
                    T.toast("请输入正确的手机号");
                    return;
                }
                if (InputControl.isEmpty(passwordEt)) {
                    T.toast("请输入密码");
                    return;
                }
                reqAuthNeedBind();
                break;
            case R.id.forget:
                /* 找回密码，忘记密码 */
                Intent intentforgetPasd = new Intent(getApplicationContext(),
                        ForgetPasdActivity.class);
                String ph = "";
                if (phoneEt.getText() != null && !phoneEt.getText().equals("")) {
                    ph = phoneEt.getText().toString();
                }
                intentforgetPasd.putExtra("tel", ph);// 将手机号码传过去
                intentforgetPasd.putExtra("title", "找回密码");
                startActivity(intentforgetPasd);
                break;
            case R.id.register:
                /* 注册 */
                Intent intentregistertPasd = new Intent(getApplicationContext(),
                        RegisterActivity.class);
                startActivity(intentregistertPasd);
                break;
            case R.id.tv_rc:
                ApplicationHelper.getInstance().switchEnv(1);
                tv_crash.setText("切换环境(当前是预发布环境)");
                T.toast("已切换到预发布环境");
                break;
            case R.id.tv_beta:
                ApplicationHelper.getInstance().switchEnv(2);
                tv_crash.setText("切换环境(当前是测试环境)");
                T.toast("已切换到测试环境");
                break;
            default:
                break;
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            finish();
        }
        return false;
    }

    OnRequestListener<User> onRequestListener = new OnRequestListener<User>() {
        @Override
        public User jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, User.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<User> response, Object tag) {
            hideProgressDialog();
            User user = response.getResponseElement();
            user.setPhone(phoneEt.getText()
                    .toString());
            user.setPassword(passwordEt.getText()
                    .toString());
            user.setAccess_token(response.getResponseElement().getAccess_token());
            user.setTag(UUID.randomUUID().toString());
            updateUser(user);


            SharedPreferences sp = getSharedPreferences(
                    Constant.USERINFO, Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putString(Constant.MOBILE, phoneEt.getText()
                    .toString());
            editor.putString(Constant.PASSWORD, passwordEt.getText()
                    .toString());
            editor.putString("accountId", user.getAccountId());
            editor.putString("access_token", user.getAccess_token());
            editor.commit();
            MessageCentre.getInstance().sendAlias(user.getPhone());
            RequestTag requestTag = (RequestTag) tag;
            //在重新登录后，是同一账号，才会退回到上一页 && requestTag.action > 0
            if (isRelogin && requestTag.action > 0) {
                setReloginBack(false);
                setResult(RESULT_OK);
                finish();
                return;
            }
            if (isBackLast) {
                setReloginBack(false);
                setResult(RESULT_OK);
                finish();
                return;
            }
            reqMerchantList();
        }
    };

    private OnRequestListener<List<MerChantInfo>> onMerchantRequestListener = new OnRequestListener<List<MerChantInfo>>() {
        @Override
        public List<MerChantInfo> jsonToObj(String responseStr) {
            MerchantMember merchantMember = JsonUtils.fromJson(responseStr, MerchantMember.class);
            ArrayList<String> disabledResources = null;
            List<MerChantInfo> mcis = new ArrayList<MerChantInfo>();
            if (merchantMember != null && merchantMember.getEmployees() != null && merchantMember.getEmployees().size() != 0) {//
                List<StaffInfo> list = merchantMember.getEmployees();
                disabledResources = merchantMember.getDisabledResources();

                if (list != null)
                    for (int i = 0; i < list.size(); i++) {
                        StaffInfo staffInfo = list.get(i);
                        if (staffInfo != null) {
                            MerChantInfo mc = staffInfo.getMerchant();
                            if (mc != null) {
                                staffInfo.setMerchant(null);

                                mc.setStaffInfo(staffInfo);
                                if (mc.isOwned()) {
                                    mc.setDisabledResources(disabledResources);
                                }
                                mcis.add(mc);
                            }
                        }
                    }

            } else {
                BaseApplication.getInstance().putMerchant(new MerChantInfo());
            }
            BaseApplication.getInstance().updateMerchants(mcis);
            BaseApplication.getInstance().putMerchantDisabledResources(disabledResources);
            return mcis;
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            logoutSuccess();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            logoutSuccess();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<List<MerChantInfo>> response, Object tag) {
            hideProgressDialog();
            gotoPage();
        }
    };


    /**
     * 登录
     */
    private void login() {
        RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();
        data.setCmd(AppSupplyRouterConstant.CMD_LOGIN);
        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
        Map<String, String> map = new HashMap<>();
        map.put("username", phoneEt.getText().toString());
        map.put("password", passwordEt.getText().toString());
        map.put("clientId", "supply-android");
        map.put("clientSecret", "supply-android-secret");
        map.put("scope", "supply-android");
        data.setParameters(map);
        String phone = getUser().getPhone();
        RequestTag requestTag = new RequestTag();
        requestTag.tag = AppSupplyRouterConstant.CMD_LOGIN;
        if (phoneEt.getText().toString().trim().equals(phone)) {
            requestTag.action = 1;
        } else {
            requestTag.action = -1;
        }
        ApplicationHelper.isHomeActivityAlive = true;
        request(data, requestTag, onRequestListener);
    }

    /**
     *
     */
    public void reqMerchantList() {
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(AppSupplyRouterConstant.cmd_account_merchant_afterLogin);
        request(RequestEntityMapSupply, AppSupplyRouterConstant.cmd_account_merchant_afterLogin, onMerchantRequestListener);
    }

    /**
     * 账号已绑定配送管理系统接口
     */
    private void reqAuthNeedBind() {
        RequestEntityMapSupply requestEntityMapSupply = new RequestEntityMapSupply();
        requestEntityMapSupply.setCmd(AppSupplyRouterConstant.cmd_auth_need_bind);
        requestEntityMapSupply.putParameter("phone", phoneEt.getText().toString());

        request(requestEntityMapSupply, AppSupplyRouterConstant.cmd_auth_need_bind, new OnRequestListener<Map<String, Object>>() {
            @Override
            public Map<String, Object> jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, new TypeToken<Map<String, Object>>() {
                }.getType());
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                hideProgressDialog();
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                hideProgressDialog();
            }

            @Override
            public void onStart(Object tag) {
                showProgressDialog();
            }

            @Override
            public void onResponse(ResponseEntity<Map<String, Object>> response, Object tag) {
                Map<String, Object> responseElement = response.getResponseElement();
                boolean isAuth = (boolean) responseElement.get("isAuth");
                if (isAuth) {
                    login();
                } else {
                    T.toast("抱歉，您的账号已绑定配送管理系统，无法使用批发端！");
                }
            }
        });
    }


    @Override
    protected void onDestroy() {
        RequestManager.getInstance().cancel("login");
        onRequestListener = null;
        BaseApplication.loginActivityCount--;
        if (BaseApplication.loginActivityCount < 0) {
            BaseApplication.loginActivityCount = 0;
        }
        super.onDestroy();
    }

    public void logoutSuccess() {
        MMKV.defaultMMKV().encode("token", "");
        MMKV.defaultMMKV().encode("toIndex", -1);
        MessageCentre.getInstance().logoutAlias();
        SharedPreferences user = getSharedPreferences(
                "userinfo", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = user.edit();
        editor.putString("password", "");
        editor.putString("accountId", "");
        editor.putString("access_token", "");
        editor.commit();
        clearUser();
        clearStoreInfo();
        BaseApplication.getInstance().putMerchant(null);
    }


    @Override
    public void onBackPressed() {

        if (isRelogin) {
            setReloginBack(true);
        } else {
            setReloginBack(false);
            super.onBackPressed();
        }
    }
}
